package com.example.autopia.view.Activities

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.autopia.R
import com.example.autopia.databinding.ActivityAddBalanceBinding
import com.example.autopia.databinding.ViewholderCardBinding
import com.example.autopia.model.Item.Card
import com.example.autopia.model.Repositories.TestRepository
import com.example.autopia.model.Repositories.UsersRepository
import com.example.autopia.utilities.PreferenceManager
import com.example.autopia.view.Adapters.CardAdapter
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase

class AddBalanceActivity : AppCompatActivity() {

    private lateinit var binding: ActivityAddBalanceBinding
    private val usersRepository = UsersRepository()
    private val adapter = CardAdapter()
    private var cardList = ArrayList<Card>()
    private var currentBalance = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAddBalanceBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.CardList.adapter=adapter
        adapter.setData(TestRepository.getCardList())
        val snapHelper = LinearSnapHelper()
        snapHelper.attachToRecyclerView(binding.CardList)

        val userPreference: PreferenceManager = PreferenceManager(this@AddBalanceActivity)
        currentBalance = userPreference.getString("userBalance")?.toInt() ?: 0
        binding.tvCurrentBalance.text = currentBalance.toString() + "R"

        binding.etAddBalance.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val userAddBalance = binding.etAddBalance.text.toString()
                if (userAddBalance.isNotEmpty()) {
                    val addBalance = userAddBalance.toIntOrNull()
                    if (addBalance != null) {
                        val balance = currentBalance + userAddBalance.toInt()
                        binding.tvBalanceAfterAdd.text = balance.toString() + "R"
                        binding.tvTotalBalance.text = userAddBalance + " руб."
                    } else {
                        // add balance не является числом
                        binding.etAddBalance.error = "Некорректный ввод"
                    }
                } else {
                    binding.tvBalanceAfterAdd.text = currentBalance.toString() + "R"
                    binding.tvTotalBalance.text = "0 руб."
                    Toast.makeText(
                        this@AddBalanceActivity,
                        "Необходимо заполнить поле",
                        Toast.LENGTH_SHORT
                    ).show()
                }

            }
            override fun afterTextChanged(s: Editable?) {
            }

        })

        var c =0
        binding.CardList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            var isScrolling = false

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE ) {
                    isScrolling = false
                    val view = snapHelper.findSnapView(binding.CardList.layoutManager)
                    view?.let { val k = binding.CardList.getChildAdapterPosition(it)
                        if(c!=k){
                            Log.d("Yatoro",k.toString())
                            c=k
                            binding.tvFI.text = cardList[c].fio
                            binding.tvCardNumber.text = cardList[c].number
                        }
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (dx != 0) {
                    isScrolling = true
                }
            }
        })
        binding.btBack.setOnClickListener {
            onBackPressed()
        }

        binding.btToCreate.setOnClickListener {
            startActivity(Intent(this@AddBalanceActivity,AddCardActivity::class.java))
        }

        binding.btAdd.setOnClickListener {
            val userAddBalance = binding.etAddBalance.text.toString()
            if (userAddBalance.isNotEmpty()) {
                val addBalance = userAddBalance.toIntOrNull()
                if (addBalance != null && addBalance!=0) {
                    usersRepository.addBalance(Firebase.auth.currentUser?.uid ?: "", userAddBalance.toInt())
                    userPreference.putString("userBalance" , (currentBalance+userAddBalance.toInt()).toString())
                    Toast.makeText(
                        this@AddBalanceActivity,
                        "Баланс пополнен",
                        Toast.LENGTH_SHORT
                    ).show()
                    finish()
                } else {
                    // add balance не является числом
                    binding.etAddBalance.error = "Некорректный ввод"
                }
            } else {
                Toast.makeText(
                    this@AddBalanceActivity,
                    "Необходимо заполнить поле",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    private fun getData() {
        val user = usersRepository.getUserById(Firebase.auth.currentUser?.uid ?: "")
        user.observe(this) { curUser ->
            val cards = ArrayList<Card>()

            if (curUser.cardList.isNullOrEmpty()) {

            } else {
                cards.addAll(curUser.cardList)
                cardList.addAll(curUser.cardList)

            }
            adapter.setData(cards)
            binding.CardList.visibility = View.VISIBLE
        }
    }

    override fun onResume() {
        super.onResume()
        getData()
    }
}